<template>
  <BasicModal
    @register="registerModal"
    :forceRender="true"
    okText="保存"
    @ok="handleOk"
    :destroyOnClose="true"
  >
    <div v-for="(item, index) in list" :key="item.uuid">
      <p class="text-xs mb-5" v-if="index !== 0">但小于</p>
      <div class="flex items-center">
        <BasicForm @register="item.Form[0]" />
        <a-button
          type="text"
          shape="circle"
          size="large"
          :icon="h(MinusCircleOutlined)"
          @click="handleDelete(item.uuid)"
        />
      </div>
    </div>
    <a-button @click="handleAdd">添加限制</a-button>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormProps } from '/@/components/Form';
  import { formList, schemas, baseFormConfig } from './addModal.data';
  import { ref, h, onMounted } from 'vue';
  import { buildUUID } from '/@/utils/uuid';
  import { MinusCircleOutlined } from '@ant-design/icons-vue';

  const [registerModal, { closeModal }] = useModalInner();
  const emits = defineEmits(['addLimits']);
  const list = ref<any>(formList);
  const handleAdd = () => {
    list.value.push({
      uuid: buildUUID(),
      Form: useForm(Object.assign({ schemas }, baseFormConfig) as FormProps),
    });
  };

  function handleDelete(uuid: string) {
    list.value = list.value.filter((item) => item.uuid !== uuid);
  }

  async function handleOk() {
    const values: Recordable[] = [];
    for (const item of list.value) {
      const { validate, getFieldsValue } = item.Form[1];
      await validate();
      values.push(getFieldsValue());
    }
    emits('addLimits', values);
    closeModal();
  }

  onMounted(() => {
    list.value = [];
  });
</script>
